<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/3/26
 * Time: 16:16
 */

namespace app\company\controller;


use app\company\model\CompanyRoleMenu;
use app\service\base\Controller;
use app\company\model\CompanyUser;
use app\company\model\CompanyMenu;


class Base extends Controller
{

    public function initialize()
    {
        parent::initialize();
        $user_id = request()->user_id;
        if ($user_id) {
            $this->user_id    = $user_id;
            $this->userInfo   = CompanyUser::where('id', $user_id)->find();
            $this->company_id = $this->userInfo->company_id;
            if($this->userInfo->is_super == 2) $this->checkAuth();//跳过管理员
        }
    }

    /**
     * @return void
     */
    protected function checkAuth(): void
    {
        $roles = $this->userInfo->companyUserRoles()->column('company_role_id');
        $menus = CompanyRoleMenu::whereIn('company_role_id', $roles)->column('company_menu_id');

        $url = explode('/', $this->request->url());// 得到 /company/user/role/list
        array_shift($url);// 删除第一个空元素
        $pop = array_pop($url);// 删除并得到最后一个元素 (按钮)
        if ($pop == "select") return;//筛选框 跳过
        $url = implode('/', $url); // 得到 company/user/role
        $c   = CompanyMenu::where('path', $url)->value('id');//菜单//得到菜单ID
        if (!in_array($c, $menus)) die(json_encode(['code' => 402, 'msg' => '无权限访问'], JSON_UNESCAPED_UNICODE));//验证菜单
        $f = CompanyMenu::where('parent_id', $c)->where('perms', $pop)->value('id');
        if (!in_array($f, $menus)) die(json_encode(['code' => 402, 'msg' => '无权限访问'], JSON_UNESCAPED_UNICODE));  //验证按钮
    }


}